// pages/createCard/createCard.js
import request from '../../../utils/config.js';
import formatDate from '../../../utils/util.js';
let WXBizDataCrypt = require('../../../utils/RdWXBizDataCrypt.js');
let hex_md5 = require('../../../utils/md5.js');
const app = getApp();
let startTime = 60;
/* 秒级倒计时 */
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    time: startTime
  });

  if (startTime <= 0) {
    that.setData({
      time: 0
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    startTime--;
    count_down(that);
  }, 1000)
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    animationData:{},
    time:0,
    returnCheckNo:"",
    errorMsg:"",
    mobileDis:true,
    isFocus: false,
    authDis:false,
    verifyStatus:'1',//"0":通过验证 "1":未验证
    showQuick:true,
    placeholderTip:"点击快速获取手机号",
    userName:"",
    bgImage: "https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/nick.png",
    userPhone: "",
    yamNo:"",
    companyName:"",
    dutyName:"",
    emailName:"",
    moreName:"",
    showImageList: new Array(),
    addressData: "",
    showNameDel:"none",
    showPhoneDel: "none",
    showYzmView:"none",
    showYzmDel:"none",
    showCompanyDel:"none",
    showDutyDel:"none",
    showEmailDel:"none",
    showSltBtm:false,
    showSltTiew:false,
    userType: '0',
    fieldList: new Array(),
    hideFiled: true,
    advfiledList: [
      { name: "合同纠纷", slt: false },
      { name: "债权债务", slt: false },
      { name: "房产纠纷", slt: false },
      { name: "建设工程", slt: false },
      { name: "知识产权", slt: false },
      { name: "交通事故", slt: false },
      { name: "婚姻家庭", slt: false },
      { name: "劳动纠纷", slt: false },
      { name: "金融证券", slt: false },
      { name: "刑事行政", slt: false },
      { name: "海事海商", slt: false },
      { name: "涉外纠纷", slt: false },
      { name: "公司企业", slt: false },
      { name: "其他", slt: false }
    ],
    animationFieldData: false,
    isTextarea: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("获取上一页面的参数=",options.id)
    if (app.globalData.userInfo){
      this.setData({
        userName: app.globalData.userInfo.nickName,
        bgImage:  app.globalData.userInfo.avatarUrl
      }); 
    }
  },

  // 点击获取本地照片
  getNativePic: function(){
    var _this = this;
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        console.log("获取照片资源返回结果=", res);
        var tempFilePaths = res.tempFilePaths[0];
        let bodyInfo = {
          path: tempFilePaths
        }
        request.requestUploadImg('pictures', bodyInfo, (res) => {
          console.log("上传图片成功=", res);
          _this.setData({
            bgImage: res.data
          });
        }, (res) => {
          console.log("上传图片失败=", res);
        })
      }
    })
  },

  //聚焦姓名输入框
  nameFocus: function(e){
    // console.log("聚焦e=",e);
    this.setData({
      showNameDel:"block"
    });
  },

  //失焦姓名输入框
  nameBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showNameDel: "none"
    });
  },

  //删除姓名
  delNameTap: function(){
    this.setData({
      userName: ""
    });
  },

  //姓名触发
  changeName: function (e) {
    this.setData({
      userName: e.detail.value
    });
  },

  //聚焦手机号输入框
  phoneFocus: function(e){
    // console.log("聚焦e=", e);
    this.setData({
      showPhoneDel: "block"
    });
  },

  //失焦手机号输入框
  phoneBlur: function(e){
    // console.log("聚焦e=", e);
    this.setData({
      showPhoneDel: "none"
    });
  },

  //删除手机号
  delPhoneTap: function(e){
    // console.log("删除手机号=",e)
    this.setData({
      showSltTiew: false,
      userPhone: ""
    });
  },

  //手机号触发
  changePhone: function (e) {
    // console.log("手机号触发=", e);
    let mobile = String(e.detail.value);
    if (mobile.length == 11) {
      if (formatDate.isValidNo(mobile)) {
        this.setData({
          userPhone: e.detail.value,
          showSltTiew: true
        });
      } else {
        this.showErrorMsg("手机号格式不正确");
        this.setData({
          userPhone: e.detail.value,
          showSltTiew: false
        });
      }
    } else {
      this.setData({
        userPhone: e.detail.value,
        showSltTiew: false
      });
    }
  },

  //获取验证码
  getAuthCode: function(){
    if (this.data.mobileDis){
      return
    }
    this.setData({
      showYzmView: "flex",
      showSltBtm:true
    });
    count_down(this);
    wx.showLoading({
      title: '加载中',
    });
    let bodyInfo = {
      "mobileNo": this.data.userPhone,
      "smsKind": 'checkNo'
    };
    request.get_api("sendMas", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取验证码成功=", res)
      if (res.data.isSuccess == 'T') {
        //保存数据
        let body = JSON.parse(res.data.body);
        this.setData({
          returnCheckNo: body.checkNo
        });
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取验证码失败=", res)
    });
  },

  //聚焦验证码输入框
  yzmFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showYzmDel: "block"
    });
  },

  //失焦验证输入框
  yzmBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showYzmDel: "none"
    });
  },

  //删除验证码
  delYzmTap: function () {
    this.setData({
      yamNo: ""
    });
  },

  //验证码触发
  yzmAuth: function (e) {
    this.setData({
      yamNo: e.detail.value
    });
    if (String(e.detail.value).length == 6) {
      if (hex_md5(e.detail.value) == this.data.returnCheckNo) {
        this.setData({
          verifyStatus:'0',
          mobileDis: true,
          authDis: true
        });
        wx.showToast({
          title: '验证成功',
          icon: 'success',
          duration: 2000
        })
      } else {
        this.showErrorMsg("验证码不正确");
      }
    }
  },

  //聚焦公司名称输入框
  companyFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showCompanyDel: "block"
    });
  },

  //失焦公司名称输入框
  companyBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showCompanyDel: "none"
    });
  },

  //删除公司名称
  delCompanyTap: function () {
    this.setData({
      companyName: ""
    });
  },

  //公司名称触发
  companyTap: function (e) {
    this.setData({
      companyName: e.detail.value
    });
  },

  //聚焦职务输入框
  dutyFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showDutyDel: "block"
    });
  },

  //失焦职务输入框
  dutyBlur: function (e) {
    // console.log("失焦e=", e);
    this.setData({
      showDutyDel: "none"
    });
  },

  //删除职务
  delDutyTap: function () {
    this.setData({
      dutyName: ""
    });
  },

  //职务触发
  dutyTap: function (e) {
    this.setData({
      dutyName: e.detail.value
    });
  },

  //公司名称触发
  companyTap: function (e) {
    this.setData({
      companyName: e.detail.value
    });
  },

  //聚焦邮箱输入框
  emailFocus: function (e) {
    // console.log("聚焦e=",e);
    this.setData({
      showEmailDel: "block"
    });
  },

  //失焦邮箱输入框
  emailBlur: function (e) {
    console.log("失焦e=", e.detail.value);
    if (!e.detail.value) {
      this.setData({
        showEmailDel: "none"
      });
    } else {
      if (formatDate.fChkMail(e.detail.value)) {
        this.setData({
          showEmailDel: "none"
        });
      } else {
        this.showErrorMsg("邮箱格式不正确");
      }
    }
  },

  //删除邮箱
  delEmailTap: function () {
    this.setData({
      emailName: ""
    });
  },

  //邮箱触发
  emailTap: function (e) {
    this.setData({
        emailName: e.detail.value
    });
  },

  //绑定更多数据
  moreTap: function(e){
    this.setData({
      moreName: e.detail.value
    });
  },

  //开始创建卡片
  createCardNow: function(){
    // console.log(this.data.fieldList);
    if (!this.data.userName){
      this.showErrorMsg("请输入姓名");
    } else if (!this.data.userPhone){
      this.showErrorMsg("请输入手机号");
    } else if (!this.data.companyName){
      this.showErrorMsg("请输入公司名称");
    } else if (!this.data.dutyName){
      this.showErrorMsg("请输入职务名称");
    } else{
      if (this.data.emailName) {
        if (!formatDate.fChkMail(this.data.emailName)) {
          this.showErrorMsg("请输入正确的邮箱");
        } else {
          wx.showLoading({
            title: '加载中'
          })
          let fieldList = "";
          if (this.data.fieldList.length > 0) {
            fieldList = this.data.fieldList.join();
          }
          let bodyInfo = {
            "openid": app.globalData.openid,
            "avatarUrl": this.data.bgImage,
            "userName": this.data.userName,
            "mobileNo": this.data.userPhone,
            'verifyStatus': this.data.verifyStatus,
            'lawfirmName': this.data.companyName,
            'title': this.data.dutyName,
            'email': this.data.emailName,
            'userType': this.data.userType,
            'status': '0',
            'advField': fieldList,
            'moreExt': this.data.moreName
          };
          request.post_api("modifyUserInfo", bodyInfo, (res) => {
            wx.hideLoading();
            console.log("完善信息成功=", res)

            if (res.data.isSuccess == 'T') {
              //保存数据    
              app.globalData.persionalInfo = JSON.parse(res.data.body);
              wx.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 1500
              })
              wx.navigateBack();
              app.globalData.identity = "";
            }
          }, (res) => {
            wx.hideLoading();
            console.log("完善信息失败=", res)
          });
        }
      } else {
        wx.showLoading({
          title: '加载中'
        })
        let fieldList = "";
        if (this.data.fieldList.length > 0) {
          fieldList = this.data.fieldList.join();
        }
        let bodyInfo = {
          "openid": app.globalData.openid,
          "avatarUrl": this.data.bgImage,
          "userName": this.data.userName,
          "mobileNo": this.data.userPhone,
          'verifyStatus': this.data.verifyStatus,
          'lawfirmName': this.data.companyName,
          'title': this.data.dutyName,
          'email': this.data.emailName,
          'userType': this.data.userType,
          'status': '0',
          'advField': fieldList,
          'moreExt': this.data.moreName
        };
        request.post_api("modifyUserInfo", bodyInfo, (res) => {
          wx.hideLoading();
          console.log("完善信息成功=", res)

          if (res.data.isSuccess == 'T') {
            //保存数据    
            app.globalData.persionalInfo = JSON.parse(res.data.body);
            wx.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            })
            wx.navigateBack();
          }
        }, (res) => {
          wx.hideLoading();
          console.log("完善信息失败=", res)
        });
      }
    }
  },

  //errorMsg显示
  showErrorMsg: function(msg){
    this.setData({
      errorMsg: msg
    });
    var animation = wx.createAnimation({
      duration: 1000,
      timingFunction: 'ease',
    })
    this.animation = animation
    animation.translateY(26).step()
    this.setData({
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.translateY(-26).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 2000)
  },

  //快速获取手机号权限
  getPhoneNumber: function (e) {
    // console.log(e.detail.errMsg)
    // console.log(e.detail.iv)
    // console.log(e.detail.encryptedData)
    let _that = this;
    console.log("getPhoneNumber=",e)
    if (e.detail.errMsg == 'getPhoneNumber:fail user deny' || e.detail.errMsg == 'getPhoneNumber:fail:cancel to confirm login' || e.detail.errMsg == 'getPhoneNumber:fail:access denied' || e.detail.errMsg == 'getPhoneNumber:fail 该 appid 没有权限') {
      _that.setData({
        showQuick: false,
        placeholderTip: '请输入手机号',
        mobileDis: false,
        isFocus: true
      });
    } else {
      let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
      let decodeData = pc.decryptData(e.detail.encryptedData, e.detail.iv);
      console.log('解密后 decodeData: ', decodeData);
      _that.setData({
        userPhone: decodeData.purePhoneNumber,
        verifyStatus: '0'
      });
    }
  },

  //职务触发
  dutyTap: function (e) {
    let userType = this.data.userType;
    let companyName = this.data.companyName;
    if (e.detail.value.indexOf('律师') != -1 || this.data.companyName.indexOf('律所') != -1 || this.data.companyName.indexOf('律师') != -1) {
      userType = '1';
    } else {
      userType = '0';
    }
    this.setData({
      dutyName: e.detail.value,
      userType: userType
    });
  },

  //公司名称触发
  companyTap: function (e) {
    let userType = this.data.userType;
    let dutyName = this.data.dutyName;
    if (e.detail.value.indexOf('律所') != -1 || e.detail.value.indexOf('律师') != -1 || this.data.dutyName.indexOf('律师') != -1) {
      userType = '1';
    } else {
      userType = '0';
    }
    this.setData({
      companyName: e.detail.value,
      userType: userType
    });
  },

  //点击显示擅长领域
  showFiled: function () {
    // var animation = wx.createAnimation({
    //   duration: 800,
    //   timingFunction: 'ease',
    // })
    // this.animation = animation
    // animation.translateY('20%').step()
    this.setData({
      hideFiled: false,
      animationFieldData: true,
      isTextarea: false
    });
  },

  //点击擅长
  selectItems: function (e) {
    console.log(e)
    let index = e.target.dataset.key;
    let temFieldList = this.data.advfiledList;
    if (temFieldList[index].slt) {
      temFieldList[index].slt = false;
      temFieldList[index].imgSlt = false;
    } else {
      let tempIndex = 0;
      temFieldList.forEach(function (e) {
        if (e.slt) {
          tempIndex++
        }
      });
      if (tempIndex < 4) {
        temFieldList[index].slt = true;
        temFieldList[index].imgSlt = true;
      }
    }
    this.setData({
      advfiledList: temFieldList
    });
  },

  //取消擅长领域
  cancleField: function () {
    // var animation = wx.createAnimation({
    //   duration: 500,
    //   timingFunction: 'ease',
    // })
    // this.animation = animation
    // animation.translateY('-100%').step()
    this.setData({
      animationFieldData: false,
      hideFiled: true,
      isTextarea: true
    });
  },

  //确定擅长领域
  confirmField: function () {
    let temFieldList = this.data.advfiledList;
    let filedList = new Array();
    temFieldList.forEach(function (e) {
      if (e.slt) {
        filedList.push(e.name);
      }
    });
    console.log("filedList=", filedList)
    // if (filedList.length > 0) {
      // var animation = wx.createAnimation({
      //   duration: 500,
      //   timingFunction: 'ease',
      // })
      // this.animation = animation
      // animation.translateY('-100%').step()
      this.setData({
        animationFieldData: false,
        fieldList: filedList,
        hideFiled: true,
        isTextarea: true
      });
    // }
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  }

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  
  // }
})